<template>
	<view class="clock_in">
		<view class="clock_in_time">
			<view class="dayTime_time">
				{{dayTime.time}}
			</view>
			<view class="dayTime_day">
				<text>{{dayTime.day}}</text>
				<text style="margin-left: 20rpx;">{{dayTime.week}}</text>
			</view>
		</view>
		<view class="clock_in_summary">
			<view>
				<image src="../static/clockIn/address.png" mode="" style="width:220rpx;height: 220rpx;"></image>
			</view>
			<view style="margin-top: 10rpx;">
				有效距离 {{punchPage.radius}} 米
			</view>
		</view>
		<view class="clock_in_statistics">
			<view class="clock_in_statistics_left">
				<view class="clock_in_statistics_left_value">
					<text style="font-size: 40rpx;">{{punchPage.mouthSignInCount}}</text>次
				</view>
				<view class="clock_in_statistics_left_label">
					月累计打卡
				</view>
			</view>
			<view class="clock_in_statistics_right">
				<view class="clock_in_statistics_right_value">
					<text style="color:red;font-size: 40rpx;">{{punchPage.mouthAbnormalCount}}</text>次
				</view>
				<view class="clock_in_statistics_right_label">
					月迟到早退
				</view>
			</view>
		</view>
		<view style="font-size: 28rpx;text-align: center;font-weight:bold;" v-if="!isDistance && location.distance">
			您目前不在打卡范围内，距离 {{Math.round(location.distance*1000)}} 米
		</view>
		<view style="font-size: 28rpx;text-align: center;font-weight:bold;margin:10rpx"
			v-if="!punchPage.isBtnGrey && isDistance">
			<text :style="{color: typeStatus==0?'green':'red'}">{{typeDesc}}</text>
		</view>
		<view class="clock_in_refresh">
			<template v-if="!punchPage.isBtnGrey && isDistance">
				<view @click="handleClock">
					<view style="margin-top: 20rpx;">
						<image src="../static/clockIn/clock_active.png" mode="" style="width:130rpx;height: 130rpx;">
						</image>
					</view>
					<view style="color: #0293fe;">
						打卡
					</view>
				</view>
			</template>
			<template v-else>
				<view>
					<view style="margin-top: 20rpx;">
						<image src="../static/clockIn/clock.png" mode="" style="width:130rpx;height: 130rpx;"></image>
					</view>
					<view style="color: #8a8a8a;">
						打卡
					</view>
				</view>
			</template>
		</view>
		<view class="clock_in_menu">
			<view class="clock_in_menu_box" @click="handleSelected(1)">
				<view>
					<image v-if="current==1" src="../static/clockIn/refresh.png" mode=""
						style="width:60rpx;height: 60rpx;"></image>
				</view>
				<view :class="{active:current==1}">
					刷新
				</view>
			</view>
			<view class="clock_in_menu_box" @click="handleSelected(2)">
				<view>
					<image v-if="current!=2" src="../static/clockIn/record.png" mode=""
						style="width:60rpx;height: 60rpx;"></image>
				</view>
				<view :class="{active:current==1}">
					记录
				</view>
			</view>
		</view>
		<ShowModal v-model="showOpen" title="" :mData="modalData" type="customBtn" @onConfirm="onConfirm"
			:showCancel="false" :maskEnable="false">
			<view>
				<uni-forms :modelValue="valiFormData" ref="uForm" :rules="rules">
					<uni-forms-item label="原因" name="remark" required>
						<uni-easyinput type="textarea" v-model="valiFormData.remark"
							placeholder="请填写原因"></uni-easyinput>
					</uni-forms-item>
				</uni-forms>
			</view>
		</ShowModal>
	</view>
</template>

<script setup>
	import {
		ref,
		onMounted,
		onUnmounted
	} from 'vue'
	import {
		onReady,
		onShow
	} from '@dcloudio/uni-app'
	import {
		dayjs
	} from '@/uni_modules/iRainna-dayjs/js_sdk/dayjs.min.js'
	import ShowModal from "../../pages/show-modal/index.vue"
	import {
		getAction,
		postAction,
		postFormAction
	} from "@/utils/request.js";

	const times = ref(null)
	const dayTime = ref({})
	const current = ref(1)
	const location = ref({})
	const punchPage = ref({})
	const isDistance = ref(false)
	const typeDesc = ref('')
	const typeStatus = ref(0)
	const punchId = ref(-1)
	const showOpen = ref(false)
	const modalData = ref({
		title: "",
		confirmText: "确定",
	})
	const valiFormData = ref({
		remark: "",
	})
	const rules = {
		remark: {
			rules: [{
				required: true,
				errorMessage: '原因不能为空'
			}]
		}
	}
	const uForm = ref(null)
	// 必须要在onReady生命周期，因为onLoad生命周期组件可能尚未创建完毕
	onReady(() => {
		uForm.value.setRules(rules);
	})

	onMounted(() => {
		init()
		initTime()
	})
	onUnmounted(() => {
		if (times.value) {
			clearInterval(times.value)
		}
	})
	onShow(() => {
		init()
	})
	async function init() {
		uni.showLoading({
			title: '加载中'
		});
		const res = await postAction('/m/hr/punchPage')
		typeDesc.value = res.data.typeDesc;
		typeStatus.value = res.data.typeStatus;
		punchPage.value = res.data || {}
		uni.hideLoading()
		getLocation()
		if (res.data.isBtnGrey) {
			uni.showToast({
				title: typeDesc.value,
				icon: 'none',
			})
		}
	}

	function initTime() {
		times.value = setInterval(() => {
			dayTime.value.time = dayjs().format('HH:mm')
			dayTime.value.day = dayjs().format('YYYY年MM月DD日')
			dayTime.value.week = getWeek(dayjs())
		}, 1000)
	}

	function getWeek(date) { // 时间戳
		const week = dayjs(date).day();

		switch (week) {
			case 1:
				return '星期一';
			case 2:
				return '星期二';
			case 3:
				return '星期三';
			case 4:
				return '星期四';
			case 5:
				return '星期五';
			case 6:
				return '星期六';
			case 0:
				return '星期天';
		}
	}

	function handleSelected(val) {
		if (val == 2) {
			const record = {
				code: 'kaoqin_time_sign',
			}
			uni.navigateTo({
				url: `/application/moduleList?record=${JSON.stringify(record)}`,
			});
		} else {
			init()
		}
	}

	function handleRefresh() {
		uni.showToast({
			title: '刷新了',
			icon: 'none'
		})
	}

	function handleClock() {
		const params = {
			lng: location.value.longitude,
			lat: location.value.latitude,
			type: punchPage.value.type,
			photoCount: punchPage.value.photoCount,
		}
		if (punchPage.value.photoCount > 0) {
			uni.navigateTo({
				url: `/cmn/clockIn/ClockInForm?record=${JSON.stringify(params)}`
			})
			return
		}
		uni.showModal({
			title: '确定打卡吗？',
			success: async (e) => {
				if (e.confirm) {
					console.log('params', params);
					const res = await postFormAction('/m/hr/punch', params);
					console.log('res', res);
					if (res.code == 500) {
						uni.showToast({
							title: res.msg,
							icon: 'none'
						})
					} else {
						let result = res.data.result;
						punchId.value = res.data.id;
						let min = res.data.min;
						let desc = '';
						if (result == 1) {
							desc = '迟到' + min + '分钟';
						} else if (result == 2) {
							desc = '早退' + min + '分钟';
						}

						if (result != 0) {
							handleShowOpen();
						} else {
							uni.showModal({
								title: '提示',
								content: '打卡成功',
								success: function(suc) {
									if (suc.confirm) {
										callBack()
									} else if (suc.cancel) {
										callBack()
									}
								}
							});
						}
						// uni.showToast({
						// 	title: '已打卡',
						// 	icon: 'none'
						// })
					}
				}
			}
		})
	}

	function postRemark(punchId, desc) {
		uni.showModal({
			title: desc, //提示内容
			placeholderText: '请填写原因', //输入提示
			showCancel: false,
			editable: true,
			success: async function(suc) {
				if (suc.confirm) {
					const {
						content
					} = suc
					if (content == '') {
						uni.showToast({
							title: '请填写原因',
							icon: 'none',
						})
						postRemark(punchId, desc);
						return;
					}
					console.log('content', content);
					uni.showLoading({
						title: '加载中'
					});
					const params = {
						id: punchId,
						remark: content,
					}
					console.log('params', params);
					postFormAction('/m/hr/punchRemark', params).then((
							res) => {
							uni.hideLoading()
							uni.showToast({
								icon: "none",
								title: '操作成功',
							});
							callBack()
						})
						.catch((e) => {
							uni.showToast({
								icon: "none",
								title: e.message,
							});
						});
				} else if (suc.cancel) {
					callBack()
				}
			}
		});
	}
	//打开modal
	function handleShowOpen() {
		valiFormData.value.remark = undefined;
		modalData.value.title = '提示';
		showOpen.value = true;
		uForm.value.clearValidate()
	}
	//modal回调
	function onConfirm() {
		uForm.value.validate().then(res => {
			console.log("valiFormData", valiFormData.value, res)
			uni.showLoading({
				title: '加载中'
			});
			const params = {
				id: punchId.value,
				remark: valiFormData.value.remark,
			}
			console.log('params', params);
			postFormAction('/m/hr/punchRemark', params).then((
					res) => {
					uni.hideLoading()
					uni.showModal({
						title: '提示',
						content: '操作成功',
						success: function(suc) {
							if (suc.confirm) {
								callBack()
							} else if (suc.cancel) {
								callBack()
							}
						}
					});
				})
				.catch((e) => {
					uni.hideLoading()
					uni.showToast({
						icon: "none",
						title: e.message,
					});
				});
			showOpen.value = false;
		}).catch(err => {
			console.log('err', err);
		})
	}

	function getLocation() {
		console.log("开始定位")
		uni.getLocation({
			type: "wgs84", // "gcj02" 需配置sdk才支持
			isHighAccuracy: true, //高精度
			// geocode:true,
			success: async function(res) {
				console.log('getLocation res', res);
				location.value = res
				location.value.distance = await GetDistance(punchPage.value.lngLoc, punchPage.value
					.latLoc)
				if (location.value.distance * 1000 < (punchPage.value.radius - 0)) {
					isDistance.value = true
				}
			},
			fail(e) {
				console.log("定位失败", e)
				uni.showToast({
					title: '获取位置信息失败，无法使用定位功能',
					icon: 'none',
				})
			}
		});
	}
	//进行经纬度转换为距离的计算
	function Rad(d) {
		return d * Math.PI / 180.0; //经纬度转换成三角函数中度分表形式。
	}
	//计算距离，经度 纬度
	async function GetDistance(lng1, lat1) {
		const res = {
			lat: location.value.latitude,
			lng: location.value.longitude
		}
		console.log(res.lat, res.lng, '自己的位置');
		console.log(lat1, lng1);
		let lat2 = res.lat; //维度
		let lng2 = res.lng; //经度
		var radLat1 = Rad(lat1);
		var radLat2 = Rad(lat2);
		var a = radLat1 - radLat2;
		var b = Rad(lng1) - Rad(lng2);
		var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) +
			Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
		s = s * 6378.137; // EARTH_RADIUS;
		s = Math.round(s * 10000) / 10000; //输出为公里
		//s=s.toFixed(4);
		console.log(s, '公里');
		return s;
	}
	/*返回上一页*/
	function callBack() {
		// var pages = getCurrentPages();
		// var currPage = pages[pages.length - 1]; //当前页面
		// var prevPage = pages[pages.length - 2]; //上一个页面
		uni.navigateBack();
	}
</script>
<style lang="scss" scoped>
	.clock_in {
		height: 100%;
		display: flex;
		flex-direction: column;
		justify-content: space-between;

		&_time {
			width: 100%;
			text-align: center;

			.dayTime_time {
				margin: 40rpx 0 20rpx 0;
				font-size: 80rpx;
				font-weight: bold;
			}
		}

		&_summary {
			color: #0293fe;
			text-align: center;
			margin: 30rpx 0 30rpx 0;
			font-weight: bold;
		}

		.clock_in_statistics {
			display: flex;

			&_left {
				width: 50%;
				padding-right: 40rpx;
				border-right: 1px solid #ccc;
				display: flex;
				flex-direction: column;
				align-items: flex-end;

				&_label {
					width: 100px;
					text-align: center;
				}

				&_value {
					margin-bottom: 10rpx;
					width: 100px;
					text-align: center;
				}
			}

			&_right {
				width: 50%;
				padding-left: 40rpx;

				&_label {
					width: 284rpx;
					text-align: center;
				}

				&_value {
					margin-bottom: 10rpx;
					width: 284rpx;
					text-align: center;
				}
			}
		}

		.clock_in_refresh {
			text-align: center;
			margin-top: 40rpx;
		}

		.clock_in_menu {
			display: flex;
			justify-content: space-around;
			padding: 20rpx;

			&_box {
				text-align: center;
				color: #e5e5e5;
			}
		}

		.active {
			color: #0094ff;
		}
	}
</style>